from django.db import models
from django.contrib.auth.hashers import make_password, check_password
from django.core.validators import EmailValidator
from django.core.exceptions import ValidationError

class Role(models.Model):
    name = models.CharField(
        max_length=50,
        unique=True,
        verbose_name="角色名称",
        help_text="角色的唯一标识名称"
    )
    description = models.TextField(
        max_length=500,
        blank=True,
        verbose_name="角色描述",
        help_text="角色的详细描述"
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="创建时间"
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="更新时间"
    )

    class Meta:
        verbose_name = "角色"
        verbose_name_plural = "角色管理"

    def __str__(self):
        return self.name

    @classmethod
    def create_default_roles(cls):
        """创建默认角色"""
        default_roles = [
            ("admin", "系统管理员，拥有所有权限"),
            ("manager", "管理员，拥有大部分管理权限"),
            ("user", "普通用户，拥有基本权限"),
            ("guest", "访客，拥有有限权限")
        ]
        for name, description in default_roles:
            cls.objects.get_or_create(
                name=name,
                defaults={'description': description}
            )

class User(models.Model):
    userId = models.AutoField(
        primary_key=True, 
        verbose_name="用户ID", 
        help_text="系统自动生成的用户唯一标识"
    )
    username = models.CharField(
        max_length=150, 
        unique=True, 
        verbose_name="用户名", 
        help_text="用户的登录名，必须唯一"
    )
    userEmail = models.EmailField(
        max_length=255, 
        unique=True, 
        verbose_name="用户邮箱", 
        help_text="用于接收通知的邮箱地址，必须唯一"
    )
    cellPhone = models.CharField(
        max_length=15, 
        unique=True, 
        verbose_name="手机号", 
        help_text="用户绑定的手机号，必须唯一"
    )
    role = models.ForeignKey(
        Role,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name="用户角色",
        help_text="用户的角色"
    )
    password = models.CharField(
        max_length=128, 
        verbose_name="密码", 
        help_text="用户的登录密码，存储为加密形式"
    )

    associated_manager = models.ForeignKey(
        'self',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='managed_users',
        verbose_name="关联管理员",
        help_text="创建该用户的管理员"
    )

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户管理"

    def __str__(self):
        return self.username

    def save(self, *args, **kwargs):
        if not self.role:
            # 如果没有指定角色，设置为默认用户角色
            default_role, _ = Role.objects.get_or_create(
                name="user",
                defaults={'description': "普通用户，拥有基本权限"}
            )
            self.role = default_role
        super().save(*args, **kwargs)

    # 密码加密
    def set_password(self, raw_password):
        """
        使用 Django 的 make_password 方法加密密码并存储。
        """
        self.password = make_password(raw_password)

    # 验证密码
    def check_password(self, raw_password):
        """
        验证给定的明文密码是否与存储的加密密码匹配。
        """
        return check_password(raw_password, self.password)
    
    # 将对象转换为 JSON 格式
    def to_json(self):
        # 获取所有关联的下层用户
        managed_users = []
        if hasattr(self, 'managed_users'):
            for user in self.managed_users.all():
                managed_users.append({
                    "userId": user.userId,
                    "username": user.username,
                    "userEmail": user.userEmail,
                    "cellPhone": user.cellPhone,
                    "userRoles": user.role.name if user.role else "user"
                })
        return {
            "userId": self.userId,
            "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
            "username": self.username,
            "userEmail": self.userEmail,
            "cellPhone": self.cellPhone,
            "userRoles": self.role.name if self.role else "user",
            "token": self.userId,
            "managed_users": managed_users # 添加关联下层用户 
        }

    # 校验邮箱
    def validate_email(self):
        """
        校验用户邮箱格式是否合法。
        """
        validator = EmailValidator(message="邮箱格式无效")
        try:
            validator(self.userEmail)
            return True
        except ValidationError as e:
            return False
        
    @classmethod
    def create_user(cls, username, userEmail, cellPhone, role_name, password, manager_id = None):
        """创建新用户的类方法"""
        role, _ = Role.objects.get_or_create(
            name=role_name,
            defaults={'description': f"用户角色: {role_name}"}
        )
        user = cls(
            username=username,
            userEmail=userEmail,
            cellPhone=cellPhone,
            role=role,
            password=password
        )
        # 设置关联管理员
        if manager_id:
            try:
                manager = cls.objects.get(userId=manager_id)
                user.associated_manager = manager
            except cls.DoesNotExist:
                pass
        user.set_password(password)
        user.save()
        return user
    
